package org.teamh.gui.engine.ogg;

public class BackgroundMusic {
	public static final String VOLUME = "volume";
	public static boolean loadedNewTrack;
	private static final float STEP = 0.02f;
	private static BackgroundMusic self = new BackgroundMusic();

	private float[] position;
	
	private Audio currentMusic;
	private Audio nextMusic;
	
	private boolean isPlaying = false;
	
	private boolean fadeIn;
	private boolean fadeOut;
	
	private float volume;
	private float maxVolume = 1.0f;
	
	private boolean waitForFadeIn;
	
	private String lastSource;
	
	private BackgroundMusic() {
		position = new float[3];
	}
	
	public static BackgroundMusic get() {
		return self;
	}
	
	public void setMaxVolume(float maxVolume) {
		this.maxVolume = maxVolume;
		volume = maxVolume;
		
		if(currentMusic != null) {
			currentMusic.setVolume(volume);
		}
	}
	
	public void setMusic(String source) {
		if(lastSource != null && lastSource.equals(source)) {
			return;
		}
		
		lastSource = source;
		
		loadedNewTrack = false;
		startFadingOut();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				nextMusic = SoundCache.getOgg(lastSource);
				BackgroundMusic.loadedNewTrack = true;
			}
		}).start();
	}
	
	public void setPosition(float[] position) {
		this.position = position;
		
		if(currentMusic != null) {
			currentMusic.setSourcePosition(position);
		}
	}
	
	public float[] getPosition() {
		return position;
	}
	
	public void update() {
		if(!isPlaying) {
			if(fadeIn) {
				if(waitForFadeIn) {
					startFadingIn();
				} else {
					if(volume > maxVolume) {
						volume = maxVolume;
						fadeIn = false;
						isPlaying = true;
					} else {
						volume += STEP;
					}
				}
			}
			
			if(fadeOut) {
				if(volume < 0) {
					volume = 0;
					startFadingIn();
				} else {
					volume -= STEP;
				}
			}
			
			if(currentMusic != null) {
				currentMusic.setVolume(volume);
			}
		} else {
			if(currentMusic != null) {
				currentMusic.setSourcePosition(position);
			}
		}
	}
	
	private void startFadingIn() {
		if(loadedNewTrack) {
			if(currentMusic != null) {
				currentMusic.stop();
			}
			currentMusic = nextMusic;
			currentMusic.play(1, 0, true, position[0], position[1], position[2]);
			waitForFadeIn = false;
		} else {
			waitForFadeIn = true;
		}
		
		fadeIn = true;
		isPlaying = false;
		fadeOut = false;
	}
	
	public void startFadingOut() {
		fadeOut = true;
		fadeIn = false;
		isPlaying = false;
	}

	public float getMaxVolume() {
		return maxVolume;
	}
}
